package com.mtons.mblog.modules.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import com.mtons.mblog.base.utils.ObjectConvertUtils;
import com.mtons.mblog.modules.service.*;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @className: PostUpdateHandler
 * @auther: Jerry
 * @date: 2021/4/6 14:34
 * @desctiption: TODO
 * @version: 1.0
 */
@Component
public class PostUpdateHandler {

    private Logger log = LoggerFactory.getLogger(PostUpdateHandler.class);

    @Autowired
    private UserEventService userEventService;
    @Autowired
    private FavoriteService favoriteService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private TagService tagService;
    @Autowired
    private MessageService messageService;

    @RabbitListener(queues = RabbitConstant.POST_UPDATE_QUEUE)
    public void handler(Message message, Channel channel) throws IOException {
        PostUpdateMessage postUpdateMessage = (PostUpdateMessage) ObjectConvertUtils.ByteToObject(message.getBody());
        log.info("PostUpdateHandler -------> mq 收到一条消息： {}", JSONObject.toJSONString(postUpdateMessage));
        switch (postUpdateMessage.getAction()) {
            case PostUpdateMessage.POST_PUBLISH:
                log.info("PostUpdateHandler -------> publish");
                userEventService.identityPost(postUpdateMessage.getUserId(), true);
                break;
            case PostUpdateMessage.POST_DELETE:
                log.info("PostUpdateHandler -------> delete");
                userEventService.identityPost(postUpdateMessage.getUserId(), false);
                favoriteService.deleteByPostId(postUpdateMessage.getPostId());
                commentService.deleteByPostId(postUpdateMessage.getPostId());
                tagService.deteleByPostId(postUpdateMessage.getPostId());
                messageService.deleteByPostId(postUpdateMessage.getPostId());
                break;
        }

        // 手动ack
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
